package com.cloud.picture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.picture.api.aliyunai.AliYunAiApi;
import com.cloud.picture.api.aliyunai.model.outpainting.CreateOutPaintingTaskRequest;
import com.cloud.picture.api.aliyunai.model.outpainting.CreateOutPaintingTaskResponse;
import com.cloud.picture.exception.BusinessException;
import com.cloud.picture.manager.upload.FilePictureUpload;
import com.cloud.picture.manager.upload.PictureUploadTemplate;
import com.cloud.picture.manager.upload.UrlPictureUpload;
import com.cloud.picture.mapper.PictureLikeMapper;
import com.cloud.picture.mapper.PictureMapper;
import com.cloud.picture.model.dto.file.UploadPictureResult;
import com.cloud.picture.model.dto.picture.*;
import com.cloud.picture.model.entity.Picture;
import com.cloud.picture.model.entity.PictureLike;
import com.cloud.picture.model.entity.Space;
import com.cloud.picture.model.entity.User;
import com.cloud.picture.model.enums.ErrorCodeEnum;
import com.cloud.picture.model.enums.PictureReviewStatusEnum;
import com.cloud.picture.model.vo.PictureVO;
import com.cloud.picture.model.vo.UserVO;
import com.cloud.picture.service.PictureService;
import com.cloud.picture.service.SpaceService;
import com.cloud.picture.service.UserService;
import com.cloud.picture.utils.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.cloud.picture.constant.FileConstants.FETCH_URL;

/**
* @author win
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-03-01 10:49:25
*/
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService{

    @Resource
    private UserService userService;
    @Resource
    private SpaceService spaceService;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private PictureLikeMapper pictureLikeMapper;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private AliYunAiApi aliYunAiApi;

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadWithUserRequest pictureUploadRequest) {
        checkParams(pictureUploadRequest, inputSource);
        User loginUser = pictureUploadRequest.getLoginUser();
        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCodeEnum.NOT_FOUND_ERROR, "空间不存在");
            // 空间拥有者才能上传
            ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCodeEnum.NO_AUTH_ERROR, "没有空间权限");
            // 校验额度
            ThrowUtils.throwIf(space.getTotalCount() >= space.getMaxCount(), ErrorCodeEnum.OPERATION_ERROR, "空间条数不足");
            ThrowUtils.throwIf(space.getTotalSize() >= space.getMaxSize(), ErrorCodeEnum.OPERATION_ERROR, "空间容量不足");
        }
        // 判断操作类型
        Long pictureId = pictureUploadRequest.getId();
        // 如果为更新操作 需要校验原图片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCodeEnum.NOT_FOUND_ERROR);
            // 只有图片创建人或者管理员才能进行更新
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCodeEnum.NO_AUTH_ERROR);
            }
            // 校验空间是否更改
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                ThrowUtils.throwIf(ObjectUtil.notEqual(spaceId, oldPicture.getSpaceId()), ErrorCodeEnum.PARAMS_ERROR,"空间id不一致");
            }
        }
        // 上传图片
        // 以用户id划分目录 改为按照空间划分
        String uploadPathPrefix;
        if (spaceId == null) {
            uploadPathPrefix = String.format("public/%s",loginUser.getId());
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        // 根据传入文件类型判断是本地上传还是URL上传
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        // 构造图片信息
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        String picName = uploadPictureResult.getPicName();
        if (CharSequenceUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        picture.setSpaceId(spaceId);
        // 补充审核信息
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        // id 存在则为更新 反之则为新增
        if (pictureId != null) {
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean res = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("total_size = total_size + " + picture.getPicSize())
                        .setSql("total_count = total_count + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCodeEnum.OPERATION_ERROR, "空间更新失败");
            }
            return picture;
        });
        return PictureVO.objToVo(picture);
    }

    private void checkParams(PictureUploadWithUserRequest pictureUploadRequest, Object obj) {
        if (obj == null || pictureUploadRequest == null) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR);
        }
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        if (CharSequenceUtil.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction",searchText));
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(id),"id",id);
        queryWrapper.eq(ObjectUtil.isNotEmpty(userId),"user_id",userId);
        queryWrapper.like(CharSequenceUtil.isNotBlank(name), "name", name);
        queryWrapper.like(CharSequenceUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(CharSequenceUtil.isNotBlank(picFormat), "pic_format", picFormat);
        queryWrapper.eq(CharSequenceUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picWidth), "pic_width", picWidth);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picHeight), "pic_height", picHeight);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picSize), "pic_size", picScale);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picScale), "pic_scale", picScale);
        queryWrapper.eq(ObjectUtil.isNotEmpty(reviewStatus), "review_status", reviewStatus);
        queryWrapper.like(CharSequenceUtil.isNotBlank(reviewMessage), "review_message", reviewMessage);
        queryWrapper.eq(ObjectUtil.isNotEmpty(reviewerId), "reviewer_id", reviewerId);
        queryWrapper.eq(ObjectUtil.isNotEmpty(spaceId), "space_id", spaceId);
        queryWrapper.isNull(nullSpaceId, "space_id");
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags","\"" + tag +"\"");
            }
        }
        queryWrapper.orderBy(CharSequenceUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);
        return queryWrapper;
    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 1. 转换
        PictureVO pictureVO = PictureVO.objToVo(picture);
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getUserById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        // 2. 返回结果
        return pictureVO;
    }

    @Override
    public Page<PictureVO> getPictureVoPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getTotal(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 1. 对象列表 => VO列表
        List<PictureVO> pictureVoList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 2. 查询
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        pictureVoList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVoList);
        // 3. 返回结果
        return pictureVOPage;
    }

    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCodeEnum.PARAMS_ERROR);
        // 校验必要参数
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        ThrowUtils.throwIf(ObjectUtil.isNull(id), ErrorCodeEnum.PARAMS_ERROR, "id不能为空");
        if (CharSequenceUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCodeEnum.PARAMS_ERROR, "url过长");
        }
        if (CharSequenceUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCodeEnum.PARAMS_ERROR, "简介过长");
        }
    }

    @Override
    public Boolean deletePicture(long id, HttpServletRequest request) {
        // 1. 校验
        ThrowUtils.throwIf(id <= 0, ErrorCodeEnum.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCodeEnum.NO_AUTH_ERROR);
        // 2. 判断是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCodeEnum.NOT_FOUND_ERROR);
        // 3. 权限认证
        checkPictureAuth(loginUser, oldPicture);
        // 4. 删除
        transactionTemplate.execute(status -> {
            boolean res = this.removeById(id);
            ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("total_size = total_size - " + oldPicture.getPicSize())
                        .setSql("total_count = total_count - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCodeEnum.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 5. 返回结果
        return true;
    }

    @Override
    public Boolean updatePicture(PictureUpdateRequest updateRequest, HttpServletRequest request) {
        // 1. 校验
        ThrowUtils.throwIf(updateRequest.getId() <= 0, ErrorCodeEnum.PARAMS_ERROR);
        Picture picture = new Picture();
        BeanUtils.copyProperties(updateRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(updateRequest.getTags()));
        this.validPicture(picture);
        // 2. 判断是否存在
        long id = updateRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCodeEnum.NOT_FOUND_ERROR);
        // 3. 审核信息
        User loginUser = userService.getLoginUser(request);
        this.fillReviewParams(picture, loginUser);
        // 4.更新
        boolean res = this.updateById(picture);
        ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR);
        return true;
    }

    @Override
    public void doPictureReview(PictureReviewRequest photoReviewRequest, User loginUser) {
        // 1. 校验
        Long id = photoReviewRequest.getId();
        Integer reviewStatus = photoReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        ThrowUtils.throwIf(id == null || reviewStatusEnum == null|| PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum), ErrorCodeEnum.PARAMS_ERROR);
        // 2. 判断是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCodeEnum.NOT_FOUND_ERROR);
        ThrowUtils.throwIf(oldPicture.getReviewStatus().equals(reviewStatus), ErrorCodeEnum.OPERATION_ERROR,"请勿重复审核");
        // 3. 更新状态
        Picture updatePicture = new Picture();
        BeanUtils.copyProperties(photoReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean res = this.updateById(updatePicture);
        ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR);
    }

    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
            picture.setReviewMessage("管理员自动通过审核");
        } else {
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public Boolean likePicture(PictureLikeRequest pictureLikeRequest) {
        // 1. 校验
        ThrowUtils.throwIf(pictureLikeRequest.getPictureId() <= 0 || pictureLikeRequest.getUserId() <= 0, ErrorCodeEnum.PARAMS_ERROR);
        // 2. 判断操作类型
        PictureLike pictureLike = new PictureLike();
        pictureLike.setPictureId(pictureLikeRequest.getPictureId());
        pictureLike.setUserId(pictureLikeRequest.getUserId());
        Long count = pictureLikeMapper.selectCount(new QueryWrapper<>(pictureLike));
        // 3. 操作数据库
        if (count > 0) {
            boolean res = pictureLikeMapper.delete(new QueryWrapper<>(pictureLike)) > 0;
            ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR);
        } else {
            boolean res = pictureLikeMapper.insert(pictureLike) > 0;
            ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR);
        }
        // 4. 返回结果
        return true;
    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 1. 校验
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(searchText == null, ErrorCodeEnum.PARAMS_ERROR,"搜索词为空");
        ThrowUtils.throwIf(count > 30, ErrorCodeEnum.PARAMS_ERROR, "最多抓取30张图片");
        // 2. 批量抓取
        String fetchUrl = String.format(FETCH_URL, searchText);
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (CharSequenceUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        }
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("页面抓取失败");
            throw new BusinessException(ErrorCodeEnum.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl_list").first();
        ThrowUtils.throwIf(ObjectUtil.isNull(div), ErrorCodeEnum.OPERATION_ERROR, "获取元素失败");
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (CharSequenceUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片地址
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex != -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 3. 上传
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            if (CharSequenceUtil.isNotBlank(namePrefix)) {
                // 设置图片
                pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            }
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest.toPictureUploadWithUserRequest(loginUser));
                log.info("图片上传成功: id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败");
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }

        // 4. 返回结果
        return uploadCount;
    }

    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        String nameRule = pictureEditByBatchRequest.getNameRule();

        ThrowUtils.throwIf(spaceId == null || CollUtil.isEmpty(pictureIdList), ErrorCodeEnum.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCodeEnum.NOT_LOGIN_ERROR);

        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCodeEnum.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCodeEnum.NO_AUTH_ERROR, "没有权限");
        }

        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if (pictureList.isEmpty()) {
            return;
        }
        pictureList.forEach(picture -> {
            if (CharSequenceUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });

        fillPictureWithNameRule(pictureList, nameRule);
        boolean res = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR);
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCodeEnum.NOT_FOUND_ERROR));
        checkPictureAuth(loginUser, picture);
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtils.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return ;
        }
        long cnt = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replace("{序号}", String.valueOf(cnt++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("图片名称规则解析失败", e);
            throw new BusinessException(ErrorCodeEnum.OPERATION_ERROR, "图片名称规则解析失败");
        }
    }

    @Override
    public Page<PictureVO> getLikedPictures(List<Long> pictureIds, long current, long size) {
        // 构建分页查询条件
        Page<Picture> page = new Page<>(current, size);
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", pictureIds);
        // 执行查询并转换VO
        Page<Picture> picturePage = this.page(page, queryWrapper);
        return getPictureVoPage(picturePage, null);
    }

    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共空间,仅图片发布者和管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCodeEnum.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间拥有者可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCodeEnum.NO_AUTH_ERROR);
            }
        }
    }
}




